package com.corner.ui.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import com.corner.app.ConsTants;
import com.corner.utils.DownLoadUtil;
import com.corner.utils.FileUtil;

/**
 * AVFile文件下载的服务
 *
 * @author Administrator
 */
public abstract class DownLoadService extends Service {

    protected static final int SD_ERROR = 2;
    protected static final int ERROR_FILE_DOWNLOAD = 1;

    protected abstract void onSucess(String filePath);

    protected abstract void onLoading(Integer percentDone);

    protected abstract void onFailed(int errorCode);


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent==null){
            return super.onStartCommand(intent, flags, startId);
        }
        if (!FileUtil.isSDCardAvaliable()) {
            onFailed(SD_ERROR);
            stopSelf();
        }
        final String filePath = intent
                .getStringExtra(ConsTants.INTENT_FILE_PATH);
        final String fileUrl = intent
                .getStringExtra(ConsTants.INTENT_FILE_URl);
        DownLoadUtil.getInstance().getFilePath(filePath, fileUrl, new DownLoadUtil.GetFileCallBack() {
            @Override
            public void onFinish(String filePath) {
                if (filePath == null) {
                    onFailed(ERROR_FILE_DOWNLOAD);
                } else {
                    onSucess(filePath);
                }
            }
        }, new DownLoadUtil.ProgressCallBack() {
            @Override
            public void hasFinish(int progress, int total) {
                onLoading(100 * progress / total);
            }
        });

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

}
